package edu.dayu.config;

import edu.dayu.annotation.Auth;
import edu.dayu.annotation.TestClass;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class AuthAspect {

    @Pointcut("@annotation(auth)")
    public void authLogin(Auth auth){

    }

    @Before("authLogin(auth)")
    public void before(JoinPoint joinPoint,Auth auth){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) attributes).getRequest();
        System.out.println(request.getHeader("token"));
    }



    /**
     * @within 用于匹配类级别的注解，会匹配拥有指定注解的类，包括其所有方法。
     * @annotation 用于匹配方法级别的注解，会匹配使用指定注解的方法，不考虑该方法所在的类。
     * @param testClass
     */
    @Pointcut("@within(testClass) || @annotation(testClass)")
    public void pointcut1(TestClass testClass){

    }

    @Before("pointcut1(testClass)")
    public void before1(TestClass testClass){
        System.out.println(11111111);
    }

    private String getDataSourceName(JoinPoint joinPoint,TestClass testClass){
        String name;
        if (testClass==null){
            Class declaringType = joinPoint.getSignature().getDeclaringType();
            TestClass typeAnnotation = (TestClass) declaringType.getAnnotation(TestClass.class);
            name = typeAnnotation.value();
        }else {
            name = testClass.value();
        }
        return name;
    }

}
